package com.clt.ess.web;

import com.clt.ess.base.Constant;
import com.clt.ess.bean.ResultMessageBeen;
import com.clt.ess.entity.*;
import com.clt.ess.service.*;
import com.clt.ess.utils.FastJsonUtil;
import com.clt.ess.utils.FileUtil;
import com.clt.ess.utils.ReadPfx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.clt.ess.utils.StringUtils.isNull;

@Controller
@RequestMapping("/apply")
public class ApplyController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @Autowired
    private ISealService sealService;
    @Autowired
    private IUnitService unitService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IApplyService applyService;
    @Autowired
    private IErrorLogService errorLogService;
    /**
     * 每次拦截到请求会先访问此函数
     * @param request http请求
     * @param response http回应
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     *访问印章申请列表
     * @param unitId 单位id
     */
    @RequestMapping(value="/list.html", method = RequestMethod.GET)
    public ModelAndView list(String unitId) {
        return applyService.applyListHandle(session,unitId);
    }

    /**
     *访问印章申请添加页面
     * @param unitId 单位id
     */
    @RequestMapping(value="/add.html",method=RequestMethod.GET,produces = "text/html;charset=UTF-8")
    public ModelAndView add(String unitId) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("apply/apply_add");

        //非空判断
        if("".equals(unitId)||unitId ==null){
            //如果空的话，返回error页面
            modelAndView.addObject("message", "访问的数据错误！");
            modelAndView.setViewName("error");
            return modelAndView;
        }

        //获取当前单位的一级单位
        Unit TopUnit = unitService.findTopUnit(unitId);
        //根据一级单位获得印章类型
        SealType sealType = new SealType();
        sealType.setTopUnitId(TopUnit.getUnitId());

        List<SealType> sealTypes = sealService.findSealType(sealType);

        modelAndView.addObject("sealTypes", sealTypes);
        modelAndView.addObject("unit",  unitService.findUnitById(unitId));
        //申请类型：申请制作印章
        modelAndView.addObject("applyType", Constant.APPLYTYPE_NEW);

        return modelAndView;
    }

    /**
     *访问印章申请添加页面
     * @param sealApply 申请信息
     */
    @RequestMapping(value="/add_do.html", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String add_do(SealApply sealApply, MultipartFile attachmentFile) {

        ResultMessageBeen messageBeen = new ResultMessageBeen();
        messageBeen.setMessage("success");

        File file  = new File(Constant.ATTACHMENT_PATH);
        //如果不存在，则创建文件夹
        if (!file.exists()) { file.mkdir(); }
        // 判断文件是否为空
        if (!attachmentFile.isEmpty()) {
            String filename = FileUtil.saveFile(attachmentFile,sealApply.getSealName());
            if(filename == null){
                errorLogService.addErrorLog("ApplyController-add_do-上传附件保存到磁盘时出现异常！");
                messageBeen.setMessage("error");
            }else{
                sealApply.setAttachment(filename);
            }
        }else{
//            messageBeen.setMessage("error");
        }
        boolean result = applyService.addSealApply(sealApply,session);

        if(!result){ messageBeen.setMessage("error"); }

        return FastJsonUtil.toJSONString(messageBeen);
    }

    /**
     *删除申请信息
     * @param sealApplyId 申请信息ID
     */
    @RequestMapping(value="/delete.html", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String sealApply_delete(String sealApplyId){

        ResultMessageBeen messageBeen = new ResultMessageBeen();
        messageBeen.setMessage("success");
        messageBeen.setBody(null);
        //要删除的申请信息ID
        SealApply sealApply  = new SealApply();
        sealApply.setSealApplyId(sealApplyId);
        //执行删除动作
        boolean result = sealService.delSealApplyById(sealApply);
        if(!result){
            messageBeen.setMessage("error");
            errorLogService.addErrorLog("ApplyController-sealApply_delete-删除申请信息时出错！");
        }
        return FastJsonUtil.toJSONString(messageBeen);
    }

    /**
     *访问印章申请重做页面
     * @param sealId 印章id
     */
    @RequestMapping(value="/repeat.html", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    public ModelAndView repeat(String sealId) {
        ModelAndView modelAndView = new ModelAndView();

        return modelAndView;
    }



    /**
     * 获取人员信息
     * @param keyword 关键词
     */
    @RequestMapping(value="/findPerson.html", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String findPerson(String keyword) {
        //结果对象
        ResultMessageBeen messageBeen = new ResultMessageBeen();
        //判断关键词是为空
        if(!"".equals(keyword) && keyword!=null){
            //根据关键词查找人员信息
            List<Person> personList = userService.findPersonListByKeyword(keyword);
            //添加数据到返回结果中
            messageBeen.setBody(personList);
            //返回结果类型为成功
            messageBeen.setMessage("ESSSUCCESS");
        }else {
            messageBeen.setMessage("ESSERROR");
            messageBeen.setBody("关键字不可为空！");
        }
        return new String(FastJsonUtil.toJSONString(messageBeen).getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
    }
    /**
     *解析pfx证书
     * @param pfxBase64 pfx证书base64编码
     * @param cerPsw 证书密码
     */
    @RequestMapping(value="/get_pfx_info.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getPfxInfo(String pfxBase64, String cerPsw){

        ResultMessageBeen messageBeen = new ResultMessageBeen();
        messageBeen.setMessage("success");
        messageBeen.setBody(null);
        if(!isNull(pfxBase64)&&!isNull(cerPsw)){
            //当证书和密码都不为空时
            Map<String,String> cerInfo = new HashMap<>();
            try {
                //解析pfx证书的信息
                cerInfo = ReadPfx.GetCertInfoFromPfxBase64(pfxBase64,cerPsw);
            } catch (Exception e) {
                errorLogService.addErrorLog("ApplyController-getPfxInfo-解析pfx证书出错-null！");
                messageBeen.setMessage("error");
                e.printStackTrace();
            }
            //证书所有人信息
            String owner = cerInfo.get("owner");

            String[] a = owner.split(", ");
            Map<String,String> ownerInfo = new HashMap<>();
            ownerInfo.put(a[a.length-1].split("=")[0],a[a.length-1].split("=")[1]);
            ownerInfo.put(a[a.length-2].split("=")[0],a[a.length-2].split("=")[1]);
            ownerInfo.put(a[a.length-3].split("=")[0],a[a.length-3].split("=")[1]);
            ownerInfo.put(a[a.length-4].split("=")[0],a[a.length-4].split("=")[1]);
            ownerInfo.put(a[a.length-5].split("=")[0],a[a.length-5].split("=")[1]);
            ownerInfo.put(a[a.length-6].split("=")[0],a[a.length-6].split("=")[1]);

            messageBeen.setBody(ownerInfo);

        }else{
            messageBeen.setMessage("error");
        }
        return new String(FastJsonUtil.toJSONString(messageBeen).getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
    }

}
